package com.example.fast.web.resolvers;

import com.example.fast.common.annotation.LoginUser;
import com.example.fast.common.constant.AppConstant;
import com.example.fast.common.exception.TokenException;
import com.example.fast.dao.UserDao;
import com.example.fast.domain.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 增加方法注入，将含有CurrentUser注解的方法参数注入当前登录用户
 */
@Component
public class LoginUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 如果参数类型是 UserInfo 并且有 LoginUser 注解则支持
        return parameter.getParameterType().isAssignableFrom(UserEntity.class) &&
                parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) {
        // 取出鉴权时存入的登录用户 Id
        Object userId = webRequest.getAttribute(AppConstant.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (userId == null) {
            throw new IllegalArgumentException("请求头信息丢失");
        }

        UserEntity userEntity = userDao.selectById((Long) userId);
        if (userEntity == null) {
            throw new TokenException("token无效");
        }
        return userEntity;
    }
}
